package com.siemens.industrial.web.mvc.dao.admin;

import com.siemens.industrial.model.admin.Event;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * Created by qupen on 2016/9/18.
 */
@Service
public class EventDao {
    @Resource
    JdbcTemplate jdbcTemplate;

    private static final String getEventListQuery = "SELECT * FROM `siemens`.`event`";
    private static final String getOneByIdQuery = "SELECT * FROM `siemens`.`event` WHERE `even_id`=?";
    private static final String addEventQuery = "INSERT INTO `siemens`.`event` (`event_id`,`event_name`,`event_type`,`event_desc`,`enabled`) VALUES (?,?,?,?,?)";
    private static final String updateEventQuery = "UPDATE `siemens`.`event` SET () WHERE `even_id`=?";
    private static final String deleteEventQuery = "DELETE FROM `siemens`.`event` WHERE `even_id`=?";
    private static final String isSubscreption = "SELECT \n" +
            "    a.event_id,\n" +
            "    a.event_name,\n" +
            "    a.event_type,\n" +
            "    a.event_desc,\n" +
            "    IF(b.user_id IS NULL, FALSE, TRUE) isChoose\n" +
            "FROM\n" +
            "    (SELECT \n" +
            "        event_id, event_name, event_type, event_desc\n" +
            "    FROM\n" +
            "        siemens.event) a\n" +
            "        LEFT JOIN\n" +
            "    (SELECT \n" +
            "        event_id, user_id\n" +
            "    FROM\n" +
            "        siemens.user_event_relation\n" +
            "    WHERE\n" +
            "        user_id = ? ) b ON a.event_id = b.event_id";

    public List<Event> getAll() {
        return jdbcTemplate.query(getEventListQuery, Event.getRowMapper());
    }

    public List<Event> findOneById(String userId) {
        return jdbcTemplate.query(getOneByIdQuery, new Object[]{userId}, Event.getRowMapper());
    }

    @Transactional
    public int updateById(String userId, Object object) {
        return jdbcTemplate.update(updateEventQuery, object, userId);
    }

    public void save(Event event) {
        jdbcTemplate.update(addEventQuery, pss -> {
                    pss.setString(1, event.getEventId());
                    pss.setString(2, event.getEventName());
                    pss.setString(3, event.getEventType());
                    pss.setString(4, event.getEventDesc());
                    pss.setInt(5, event.getEnabled());
                }
        );
    }

    @Transactional
    public int deleteEventById(String eventId) {
        return jdbcTemplate.update(deleteEventQuery, eventId);
    }

    public List<Map<String, Object>> getEventIsSubscription(String userId) {
        return jdbcTemplate.queryForList(isSubscreption,userId);
    }
}
